package org.musicmod.android.utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

import android.graphics.Bitmap;
import android.graphics.Color;

public class ColorAnalyser {

	public static int analyseFromBitmap(Bitmap bitmap) {
		return analyseFromBitmap(bitmap, 18, 28);
	}

	public static int analyseFromBitmap(Bitmap bitmap, int sampleX, int sampleY) {

		if (bitmap == null) {
			return Color.WHITE;
		}

		int color, score = 0;
		int color_r, color_g, color_b = 0;
		int color_min, color_max = 0;
		int saturation, value = 0;

		HashMap<Integer, Integer> colorsMap = new HashMap<Integer, Integer>();
		ArrayList<Integer> colorsScore = new ArrayList<Integer>();

		Bitmap resized = Bitmap.createScaledBitmap(bitmap, sampleX, sampleY,
				false);

		for (int y = 0; y < resized.getHeight(); y++) {
			for (int x = 0; x < resized.getWidth(); x++) {
				color = resized.getPixel(x, y);
				color_r = Color.red(color);
				color_g = Color.green(color);
				color_b = Color.blue(color);

				color_min = Math.min(Math.min(color_r, color_g),
						Math.min(color_g, color_b));
				color_max = Math.max(Math.max(color_r, color_g),
						Math.max(color_g, color_b));

				saturation = color_max - color_min;
				value = color_max;

				score = (saturation * saturation * value * value);

				colorsMap.put(score, color);
				colorsScore.add(score);
			}
		}

		Collections.sort(colorsScore);

		return colorsMap.get(colorsScore.get(colorsScore.size() - 1));

	}
}